package com.qiguliuxing.dts.admin.web;

import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.service.AdminOrderService;
import com.qiguliuxing.dts.admin.util.AuthSupport;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@RestController
@RequestMapping("/admin/order")
@Validated
public class AdminOrderController {
    private static final Logger logger = LoggerFactory.getLogger(AdminOrderController.class);

    @Autowired
    private AdminOrderService adminOrderService;

    /**
     * 查询订单
     *
     * @param userId
     * @param orderSn
     * @param orderStatusArray
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @RequiresPermissions("admin:order:list")
    @RequiresPermissionsDesc(menu = {"商场管理", "订单管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(Integer userId, String orderSn, String fetchCode, @RequestParam(required = false) List<Short> orderStatusArray,
                       @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->订单管理->查询,请求参数:userId:{},orderSn:{},page:{}", userId, orderSn, page);

        return adminOrderService.list(userId, orderSn, fetchCode, orderStatusArray, page, limit, sort, order);
    }

    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    @RequiresPermissions("admin:order:read")
    @RequiresPermissionsDesc(menu = {"商场管理", "订单管理"}, button = "详情")
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->订单管理->详情,请求参数:id:{}", id);

        return adminOrderService.detail(id);
    }

    /**
     * 订单退款
     *
     * @param body 订单信息，{ orderId：xxx }
     * @return 订单退款操作结果
     */
    @RequiresPermissions("admin:order:refund")
    @RequiresPermissionsDesc(menu = {"商场管理", "订单管理"}, button = "订单退款")
    @PostMapping("/refund")
    public Object refund(@RequestBody String body) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->订单管理->订单退款,请求参数,body:{}", body);

        return adminOrderService.refund(body);
    }

    /**
     * 订单退款
     *
     * @param id 订单信息，{ orderId：xxx }
     * @return 订单退款操作结果
     */
    @GetMapping("/detailRefundOrder")
    public Object detailRefundOrder(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->订单管理->订单退货子订单查询,请求参数,orderId:{}", id);

        return adminOrderService.detailRefundOrder(id);
    }

    /**
     * 提货确认操作
     *
     * @param body 订单信息，{ orderId：xxx }
     * @return 订单操作结果
     */
    @RequiresPermissions("admin:order:confirm")
    @RequiresPermissionsDesc(menu = {"商场管理", "订单管理"}, button = "提货确认")
    @PostMapping("/confirm")
    public Object confirm(@RequestBody String body) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->订单管理->订单发货,请求参数,body:{}", body);

        return adminOrderService.confirm(body);
    }


    /**
     * 发货
     *
     * @param body 订单信息，{ orderId：xxx, shipSn: xxx, shipChannel: xxx }
     * @return 订单操作结果
     */
    @RequiresPermissions("admin:order:ship")
    @RequiresPermissionsDesc(menu = {"商场管理", "订单管理"}, button = "订单发货")
    @PostMapping("/ship")
    public Object ship(@RequestBody String body) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->订单管理->订单发货,请求参数,body:{}", body);

        return adminOrderService.ship(body);
    }

    /**
     * 订单商品评论回复
     *
     * @param body 订单信息，{ orderId：xxx }
     * @return 订单操作结果
     */
    @RequiresPermissions("admin:order:reply")
    @RequiresPermissionsDesc(menu = {"商场管理", "订单管理"}, button = "订单商品回复")
    @PostMapping("/reply")
    public Object reply(@RequestBody String body) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->订单管理->订单商品回复,请求参数,body:{}", body);

        return adminOrderService.reply(AuthSupport.adminId(), body);
    }

    /**
     * 快递信息加载
     */
    @RequiresPermissions("admin:order:listShip")
    @RequiresPermissionsDesc(menu = {"商场管理", "订单管理"}, button = "快递加载")
    @GetMapping("/listShipChannel")
    public Object listShipChannel() {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->订单管理->快递信息加载");

        return adminOrderService.listShipChannel();
    }

    /**
     * 商户对账订单
     *
     * @param userId
     * @param orderSn
     * @param orderStatusArray
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @RequiresPermissions("admin:order:verifyList")
    @RequiresPermissionsDesc(menu = {"商场管理", "对账订单明细"}, button = "查询对账明细列表")
    @GetMapping("/verifyList")
    public Object verifyList(String startTime, String endTime, Integer userId, Integer brandId, Integer settlementFlag, String orderSn, String fetchCode, @RequestParam(required = false) List<Short> orderStatusArray,
                             @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit,
                             @Sort @RequestParam(defaultValue = "add_time") String sort,
                             @Order @RequestParam(defaultValue = "desc") String order) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->订单管理->查询对账明细列表,请求参数:userId:{},orderSn:{},page:{}", userId, orderSn, page);
        return adminOrderService.verifyList(dealDateFormat(startTime), dealDateFormat(endTime), userId, brandId, settlementFlag, orderSn, fetchCode, orderStatusArray, page, limit, sort, order);
    }

    @RequiresPermissions("admin:order:brandList")
    @RequiresPermissionsDesc(menu = {"商场管理", "对账订单明细"}, button = "获取商户列表")
    @GetMapping("/brandList")
    public Object brandList() {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->对账订单明细->获取商户列表");
        return adminOrderService.brandList();
    }

    @RequiresPermissions("admin:order:finishOrder")
    @RequiresPermissionsDesc(menu = {"商场管理", "对账订单明细"}, button = "结算")
    @GetMapping("/finishOrder")
    public Object finishOrder(@Param(value = "orderIdList") String orderIdList) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 商场管理->对账订单明细->结算,orderIds：{}", orderIdList);
        return adminOrderService.finishOrder(orderIdList);
    }

    /**
     * 商户对账
     */
    @RequiresPermissions("admin:order:verifyCount")
    @RequiresPermissionsDesc(menu = {"商户对账", "商户对账"}, button = "对账统计")
    @GetMapping("/verifyCount")
    public Object verifyAccounting(String startTime, String endTime, Integer brandId) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 对账统计->startTime:{},endTime:{},brandId:{}", startTime, endTime, brandId);
        return adminOrderService.verifyAccounting(dealDateFormat(startTime), dealDateFormat(endTime), brandId);
    }


    public static String dealDateFormat(String oldDate) {
        if (StringUtils.isEmpty(oldDate)) {
            return null;
        }
        Date date1 = null;
        DateFormat df2 = null;
        try {
            oldDate = oldDate.replace("Z", " UTC");
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
            Date date = df.parse(oldDate);
            SimpleDateFormat df1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
            date1 = df1.parse(date.toString());
            df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return df2.format(date1);
    }

}
